package com.example.gestureactivity;

import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;

/*
 * 在BaseActivity中复写onTouchEvent方法，计算滑动过的距离和滑动的速率
 * 在滑动的距离和速率满足一定的条件时，关闭当前Activity
 */
public abstract class BaseActivity extends FragmentActivity implements
		OnTouchListener {

	private static final String TAG = "BaseActivity";
	protected float startX;
	protected float startY;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			startX = event.getX();
			startY = event.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			Log.i(TAG, "touch: x = " + event.getX() + ", y = " + event.getY());
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			float currentX = event.getX();
			float currentY = event.getY();
			float dx = currentX - startX;
			float dy = currentY - startY;
			Log.e(TAG, "dx = " + dx + "," + "|dx| = " + Math.abs(dx)
					+ ",|dy| = " + Math.abs(dy));
			if (dx > 0 && Math.abs(dx) > Math.abs(dy)) {
				// 右划，而且水平方向的位移大于竖直方向的位移
				onFlingFinished();
			}
			break;

		}

		return super.onTouchEvent(event);
	}

	abstract void onFlingFinished();
}
